<template>
    <div>
        <el-row>

            <el-col
                ref="layoutMain"
                style="padding:0 10px;"
            >
                <el-row
                    style="height: 40px;"
                    type="flex"
                    align="middle"
                >
                    <!-- 模板显示按钮 -->
                    <!--<el-button @click="isShowLayoutTemplate = !isShowLayoutTemplate"-->
                    <!--size="mini" class="button-list-item">-->
                    <!--{{isShowLayoutTemplate ? '收起' : '模板'}}-->
                    <!--</el-button>-->
                    <!--病理编号搜索-->
                    <el-input
                        v-model="searchPathologyId"
                        placeholder="病理编号"
                        class="input-form"
                        style="margin: 0 10px"
                        size="mini"
                    >
                    </el-input>
                    <el-button
                        @click="diagnosisSearch"
                        class="button-list-item"
                        type="primary"
                        size="mini"
                    >
                        搜索
                    </el-button>
                    <!--<el-button @click="diagnosisLast" disabled-->
                    <!--class="button-list-item"-->
                    <!--type="primary" size="mini">-->
                    <!--上一个-->
                    <!--</el-button>-->
                    <!--<el-button @click="diagnosisNext" disabled-->
                    <!--class="button-list-item"-->
                    <!--type="primary" size="mini">-->
                    <!--下一个-->
                    <!--</el-button>-->
                    <!--状态-->
                    <el-tag
                        size="mini"
                        type="danger"
                        class="tag-list-item"
                        style="margin-left: 10px"
                    >
                        {{ levelLabel }}
                    </el-tag>
                    <!--打印数量-->
                    <el-tag
                        v-if="isFinished"
                        size="mini"
                        type="danger"
                        class="tag-list-item"
                    >
                        {{ '未打印' }}
                    </el-tag>
                    <!--是否收藏-->
                    <el-tag
                        size="mini"
                        type="danger"
                        class="tag-list-item"
                    >
                        {{ isCollected ? '已收藏' : '未收藏' }}
                    </el-tag>
                    <!--倒计时-->
                    <el-tag
                        v-if="isShowDeadline"
                        :type="tagDeadlineType"
                        size="mini"
                        class="tag-list-item"
                    >
                        {{ '已超时' }}
                    </el-tag>
                    <!-- 智能分析显示按钮 -->
                    <el-button
                        @click="isShowLayoutAiInfo = !isShowLayoutAiInfo"
                        size="mini"
                        class="button-list-item"
                    >
                        {{isShowLayoutAiInfo ? '收起' : '智能分析'}}
                    </el-button>
                    <el-button
                        @click="diagnosisCheckAnalysis"
                        size="mini"
                        class="button-list-item"
                    >
                        检验分析
                    </el-button>
                </el-row>

                <!--<el-form ref="qualityForm" v-model="qualityForm" label-width="100px"-->
                <!--:inline="true">-->
                <!--<el-form-item label="冰冻符合率:">-->
                <!--<el-select v-model="qualityForm.frozenCoincidenceRate"-->
                <!--placeholder="请选择" size="mini" class="quality-list-item">-->
                <!--<el-option v-for="t in frozenCoincidenceRateList"-->
                <!--:key="t.id" :label="t.label" :value="t.id">-->
                <!--</el-option>-->
                <!--</el-select>-->
                <!--</el-form-item>-->
                <!--<el-form-item label="诊断符合率:">-->
                <!--<el-select v-model="qualityForm.diagnosticAccordanceRate"-->
                <!--placeholder="请选择" size="mini" class="quality-list-item">-->
                <!--<el-option v-for="t in diagnosticAccordanceRateList"-->
                <!--:key="t.id" :label="t.label" :value="t.id">-->
                <!--</el-option>-->
                <!--</el-select>-->
                <!--</el-form-item>-->
                <!--<el-form-item label="诊断细致性:">-->
                <!--<el-select v-model="qualityForm.DiagnosticCarefulnessRate"-->
                <!--placeholder="请选择" size="mini" class="quality-list-item">-->
                <!--<el-option v-for="t in DiagnosticCarefulnessRateList"-->
                <!--:key="t.id" :label="t.label" :value="t.id">-->
                <!--</el-option>-->
                <!--</el-select>-->
                <!--</el-form-item>-->
                <!--<el-form-item label="切片质量:">-->
                <!--<el-select v-model="qualityForm.biopsyQuality"-->
                <!--placeholder="请选择" size="mini" class="quality-list-item">-->
                <!--<el-option v-for="t in biopsyQualityList"-->
                <!--:key="t.id" :label="t.label" :value="t.id">-->
                <!--</el-option>-->
                <!--</el-select>-->
                <!--</el-form-item>-->
                <!--<el-form-item label="扫描质量:">-->
                <!--<el-select v-model="qualityForm.scanQuality"-->
                <!--placeholder="请选择" size="mini" class="quality-list-item">-->
                <!--<el-option v-for="t in scanQualityList"-->
                <!--:key="t.id" :label="t.label" :value="t.id">-->
                <!--</el-option>-->
                <!--</el-select>-->
                <!--</el-form-item>-->
                <!--</el-form>-->
                <!--<el-row>-->
                <!--<el-form>-->
                <!--<el-form-item label="检查类型:" >-->
                <!--<el-select v-model="checkCategorySelected"-->
                <!--placeholder="请选择检查类型"-->
                <!--@change="checkCategoryChange"-->
                <!--:disabled="!isFirstOpinion"-->
                <!--size="mini" style="width: 210px;">-->
                <!--<el-option-->
                <!--v-for="item in checkCategoryList"-->
                <!--:key="item.id"-->
                <!--:label="item.label"-->
                <!--:value="item.id">-->
                <!--</el-option>-->
                <!--</el-select>-->
                <!--&lt;!&ndash;<el-button size="mini">&ndash;&gt;-->
                <!--&lt;!&ndash;<font-awesome-icon
                                :icon="['fas', 'microphone']">&ndash;&gt;-->
                <!--&lt;!&ndash;</font-awesome-icon>&ndash;&gt;-->
                <!--&lt;!&ndash;{{`  语音录入`}}&ndash;&gt;-->
                <!--&lt;!&ndash;</el-button>&ndash;&gt;-->
                <!--&lt;!&ndash;<el-button size="mini"
                            icon="el-icon-document">&ndash;&gt;-->
                <!--&lt;!&ndash;语音上传&ndash;&gt;-->
                <!--&lt;!&ndash;</el-button>&ndash;&gt;-->
                <!--</el-form-item>-->
                <!--</el-form>-->
                <!--</el-row>-->
                <el-row>
                    <span class="content-text">检查类型: {{ diagnosis.checkCategoryName }}</span>
                </el-row>
                <div
                    ref="baseInfo"
                    style="font-size: 12px"
                >
                    <el-row>
                        <el-col
                            v-for="info in baseInfoList"
                            :span="info.span"
                            :key="info.key"
                        >
                            <span>{{ info.label }}{{ info.value }}</span>
                        </el-col>
                    </el-row>
                </div>
                <div v-if="!isAssigned">
                    未分配
                </div>
                <div v-else>
                    <el-row
                        v-if="reportTemplateReady"
                        style="margin-top: 10px"
                        align="middle"
                        type="flex"
                        justify="space-between"
                    >
                        <el-tabs
                            v-model="opinionTabActive"
                            type="card"
                            ref="diagnosisLevelTabs"
                            :before-leave="opinionTabChange"
                        >
                            <el-tab-pane
                                v-for="item of opinionTabList"
                                :label="item.tabLabel"
                                :name="item.name"
                                :key="item.level"
                            >
                            </el-tab-pane>
                        </el-tabs>
                        <el-button
                            v-if="!isFirstOpinion"
                            :disabled="!isThisOpinionTab"
                            @click="diagnosisCopy"
                            align="right"
                            type="text"
                            size="mini"
                        >
                            复制上一级病理诊断
                        </el-button>
                    </el-row>

                    <div
                        v-if="reportTemplateReady"
                        class="container-narrow"
                    >
                        <grid-layout
                            id="custom-report"
                            :layout.sync="componentList"
                            :col-num="reportTemplateCol"
                            :row-height="28"
                            :is-draggable="false"
                            :is-resizable="false"
                            :is-mirrored="false"
                            :vertical-compact="true"
                            :use-css-transforms="true"
                        >
                            <grid-item
                                v-for="(item, index) in componentList"
                                :x="item.x"
                                :y="item.y"
                                :w="item.w"
                                :h="item.h"
                                :i="item.i"
                                :key="index"
                            >
                                <el-row
                                    v-if="item.smallType === 'space'"
                                    class="row-in-grid-item"
                                ></el-row>

                                <hr v-else-if="item.smallType === 'hr'">

                                <el-row
                                    v-else-if="item.smallType === 'text'"
                                    class="row-in-grid-item"
                                >
                                    <span :style="styleString(item.styleJson)">
                                        {{item.stringContent}}
                                    </span>
                                </el-row>

                                <el-row
                                    v-else-if="item.smallType === 'input'"
                                    class="row-in-grid-item"
                                >
                                    <div
                                        :id="item.i"
                                        style="width: 100%; height: 100%"
                                    >
                                        <el-input
                                            v-if="item.isInputArea"
                                            type="textarea"
                                            v-model="detailForm[item.i]"
                                            :autosize="{
                                                    minRows: 1,
                                                    maxRows: parseInt((item.h * 5 / 3), 10)
                                                  }"
                                            :placeholder="item.placeholder"
                                            :style="styleString(item.styleJson)"
                                            :disabled="!isThisOpinionTab"
                                            size="mini"
                                        >
                                        </el-input>
                                        <el-input
                                            v-else
                                            v-model="detailForm[item.i]"
                                            :placeholder="item.placeholder"
                                            :style="styleString(item.styleJson)"
                                            :disabled="!isThisOpinionTab"
                                            size="mini"
                                        >
                                        </el-input>
                                    </div>
                                </el-row>

                                <el-row
                                    v-else-if="item.smallType === 'selection'"
                                    class="row-in-grid-item"
                                >
                                    <div
                                        :id="item.i"
                                        style="width: 100%; height: 100%"
                                    >
                                        <el-select
                                            v-model="detailForm[item.i]"
                                            :placeholder="item.placeholder"
                                            :style="styleString(item.styleJson)"
                                            :disabled="!isThisOpinionTab"
                                            size="mini"
                                        >
                                            <el-option
                                                v-for="(t, index) in item.selectDataJson"
                                                :key="index"
                                                :label="t"
                                                :value="t"
                                            >
                                            </el-option>
                                        </el-select>
                                    </div>
                                </el-row>

                                <el-row
                                    v-else-if="item.smallType === 'special'"
                                    class="row-in-grid-item"
                                >
                                    <!--病理图像判断-->
                                    <div
                                        v-if="item.i === 'special_normal_pathologyFiles'"
                                        style="width: 100%; height: 100%"
                                    >
                                        <span style="float: left">{{item.stringContent}}</span>
                                    </div>
                                    <!--签名图像-->
                                    <div v-else-if="item.i === 'special_base_reportDoctor'">
                                        <span>{{item.stringContent}}</span>
                                    </div>
                                    <!--特殊检查-导入-->
                                    <div
                                        v-else-if="item.i === 'special_normal_import'"
                                        style="margin-left: 10px"
                                    >
                                        <el-button
                                            size="mini"
                                            type="text"
                                        >
                                            {{item.stringContent}}
                                        </el-button>
                                    </div>
                                    <div
                                        v-else-if="item.i === 'special_clearable_microFingings'"
                                        style="margin-left: 10px"
                                    >
                                        <el-button
                                            size="mini"
                                            type="text"
                                        >
                                            {{item.stringContent}}
                                        </el-button>
                                    </div>
                                    <div
                                        v-else-if="item.i === 'special_clearable_specialCheck'"
                                        style="margin-left: 10px"
                                    >
                                        <el-button
                                            size="mini"
                                            type="text"
                                        >
                                            {{item.stringContent}}
                                        </el-button>
                                    </div>
                                    <div
                                        v-else-if="item.i === 'special_clearable_diagnose'"
                                        style="margin-left: 10px"
                                    >
                                        <el-button
                                            size="mini"
                                            type="text"
                                        >
                                            {{item.stringContent}}
                                        </el-button>
                                    </div>
                                </el-row>
                            </grid-item>
                        </grid-layout>
                    </div>
                </div>
            </el-col>

            <!--TODO-->
            <el-col
                ref="layoutAiInfo"
                v-if="isShowLayoutAiInfo"
                :span="layoutAiInfoCol"
                style="float: right"
            >
                <el-card shadow="hover">
                    智能分析
                </el-card>
            </el-col>
        </el-row>
        <el-dialog
            :title="submitDialog.title"
            :visible.sync="submitDialog.visible"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            append-to-body
            width="90%"
        >
            <base-table
                ref="submitTable"
                v-loading="!submitDialog.isReady"
                :data="submitTable.data"
                :header="submitTable.header"
                :operation="submitTable.operation"
                :pageInfo="submitTable.pageInfo"
                :pageSizes="[10, 15, 20]"
                @pageJumpTo="submitTablePageJumpTo"
                @sizeChange="submitTableSizeChange"
                @handleClick="submitTableButtonClick"
            >
            </base-table>
            <span
                slot="footer"
                class="dialog-footer"
                style="text-align: right;"
            >
                <el-button
                    @click="submitDialog.visible = false"
                    size="mini"
                >关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash';
import VueGridLayout from 'vue-grid-layout';
import BaseTable from '@templates/components/BaseTable';
import diagnosisDefault from '@templates/diagnosisDefault';

const userLevelBase = [
    {
        level: 2,
        label: '初诊',
    },
    {
        level: 3,
        label: '核发',
    },
    {
        level: 4,
        label: '审核',
    },
    {
        level: 5,
        label: '终审',
    },
];
export default {
    name: 'DiagnosisDetailOpinionUnchanged',
    components: {
        GridLayout: VueGridLayout.GridLayout,
        GridItem: VueGridLayout.GridItem,
        BaseTable,
    },
    props: {
        diagnosis: {
            type: Object,
            default: diagnosisDefault,
        },
    },
    data() {
        return {
            userLevel: userLevelBase,
            isShowLayoutTemplate: true,
            layoutTemplateCol: 5,
            isShowLayoutAiInfo: false,
            isCollected: false,
            layoutAiInfoCol: 2,
            // layoutTemplate 相关
            layoutTemplateActive: 'orgTemplate',
            // layoutMain 相关
            isShowDeadline: true,

            searchPathologyId: '',

            qualityForm: {
                frozenCoincidenceRate: '',
                diagnosticAccordanceRate: '',
                DiagnosticCarefulnessRate: '',
                biopsyQuality: '',
                scanQuality: '',
            },

            dictionaryMap: [
                {
                    code: 'checkCategory',
                    array: 'checkCategoryList',
                },
                {
                    code: 'coincidenceRate',
                    array: 'frozenCoincidenceRateList',
                },
                {
                    code: 'coincidenceRate',
                    array: 'diagnosticAccordanceRateList',
                },
                {
                    code: 'careful',
                    array: 'DiagnosticCarefulnessRateList',
                },
                {
                    code: 'sliceQuality',
                    array: 'biopsyQualityList',
                },
                {
                    code: 'scanningQuality',
                    array: 'scanQualityList',
                },
            ],
            frozenCoincidenceRateList: [],
            diagnosticAccordanceRateList: [],
            DiagnosticCarefulnessRateList: [],
            biopsyQualityList: [],
            scanQualityList: [],

            checkCategorySelected: '',
            checkCategoryList: [],
            opinionTabActive: '',
            opinionTabList: [],

            // 基础信息字段列表
            baseInfoList: [
                { span: 4, value: '', key: 'name', label: '姓名：' },
                { span: 4, value: '', key: 'sexName', label: '性别：' },
                { span: 4, value: '', key: 'ageAll', label: '年龄：' },
                { span: 8, value: '', key: 'cardId', label: '身份证号：' },
                { span: 4, value: '', key: 'sendDoctor', label: '送检医生：' },
                {
                    span: 4,
                    value: '',
                    key: 'sendDepartment',
                    label: '送检科室：',
                },
                { span: 4, value: '', key: 'wardName', label: '病区名称：' },
                { span: 4, value: '', key: 'bedId', label: '床位号：' },
                {
                    span: 4,
                    value: '',
                    key: 'specimenName',
                    label: '标本名称：',
                },
                {
                    span: 4,
                    value: '',
                    key: 'specimenTypeName',
                    label: '标本类型：',
                },
                {
                    span: 4,
                    value: '',
                    key: 'specimenRegisterTime',
                    label: '标本登记时间：',
                },
            ],
            // 模板初始化完成确认
            reportTemplateReady: false,
            // 意见数据表单
            detailForm: {},
            // 意见数据缓存
            detailTemp: {},
            // 模板组件列表
            componentList: [],
            reportTemplateCol: 12,

            submitDialog: {
                title: '',
                visible: false,
                isReady: false,
            },
            submitTable: {
                data: [],
                header: [
                    {
                        label: '姓名',
                        prop: 'name',
                        width: '120',
                    },
                    {
                        label: '医生职称',
                        prop: 'medicalTitleName',
                        width: '160',
                    },
                    {
                        label: '诊断权限',
                        prop: 'levelName',
                        width: '100',
                    },
                    {
                        label: '联系电话',
                        prop: 'phone',
                        width: '140',
                    },
                    {
                        label: '擅长',
                        prop: 'speciality',
                    },
                ],
                operation: [
                    {
                        label: '提交',
                        functionKey: 'submitTableSubmitConfirm',
                        key: 'A',
                    },
                ],
                pageInfo: {
                    page: 1,
                    size: 15,
                    total: 0,
                },
            },
        };
    },

    async mounted() {
        this.searchPathologyId = this.diagnosisPathologyId;
        this.dictionariesRequest(this.dictionaryMap);
        // 当前标签页显示确认
        this.opinionTabActive = `${this.diagnosisLevel}`;
        // 从诊断详情获取用户列表，再请求用户数据
        /* eslint no-await-in-loop:0 */
        for (let i = 0; i < this.diagnosis.diagnosisDetailList.length; i++) {
            const t = this.diagnosis.diagnosisDetailList[i];
            const levelItem = this.userLevel.find(
                (item) => item.level === t.currentLevel
            );
            const res = await this.$axios({
                method: 'GET',
                url: `/PROXY-Remote/users/${t.doctorId}`,
            });

            let doctorName = '';
            if (res && res.data.code === 200) {
                doctorName = _.get(res.data.data, 'userInfo.name', '');
            }

            levelItem.tabLabel = `${levelItem.label}(${doctorName})`;
            levelItem.name = `${levelItem.level}`;
            this.opinionTabList.push(levelItem);
        }
        // 基本信息格式化
        this.baseInfoList.forEach((info, index) => {
            this.baseInfoList[index].value = _.get(
                this.diagnosis,
                info.key,
                ''
            );
        });

        this.checkCategorySelected = this.diagnosis.checkCategory;
        this.reportTemplateRequest();
    },
    computed: {
        layoutMainCol() {
            const layoutTemplateCol = this.isShowLayoutTemplate
                ? this.layoutTemplateCol
                : 0;
            const layoutAiInfoCol = this.isShowLayoutAiInfo
                ? this.layoutAiInfoCol
                : 0;
            return 24 - layoutTemplateCol - layoutAiInfoCol;
        },
        tagDeadlineType() {
            return 'danger';
        },
        specialExtraCount() {
            return 1;
        },
        techExtraCount() {
            return 1;
        },
        // isCollected() {
        //   return false;
        // },
        canAddExtraProject() {
            return this.isTheseDoctor;
        },
        levelLabel() {
            return _.get(this.diagnosis, 'currentLevelLabel', '');
        },

        subgroupId() {
            return _.get(this.diagnosis, 'subgroupId', 0);
        },
        diagnosisId() {
            return _.get(this.diagnosis, 'id', 0);
        },
        diagnosisPathologyId() {
            return _.get(this.diagnosis, 'pathologyId', '');
        },
        diagnosisLevel() {
            return _.get(this.diagnosis, 'currentLevel', 0);
        },
        diagnosisPrevLevel() {
            return _.get(
                this.detailGetByLevel(this.diagnosisLevel),
                'prevLevel',
                1
            );
        },
        isNeedFinalJudge() {
            return this.diagnosisLevel.canFinalVerify;
        },
        isAssigned() {
            return this.diagnosisLevel !== 1;
        },
        isFinished() {
            return this.diagnosisLevel === 6;
        },
        isFirstOpinion() {
            return this.diagnosisPrevLevel === 1;
        },
        isThisDoctor() {
            const { state } = this.$store;
            const level = this.isFinished
                ? this.diagnosisPrevLevel
                : this.diagnosisLevel;
            const detail = this.detailGetByLevel(level);
            return detail ? state.user.id === detail.doctorId : false;
        },
        isTheseDoctor() {
            const { state } = this.$store;
            const userId = state.user.id;
            return this.diagnosis.diagnosisDetailList.some(
                (t) => t.doctorId === userId
            );
        },
        isThisOpinionTab() {
            return (
                parseInt(this.opinionTabActive, 10) === this.diagnosisLevel &&
                this.isThisDoctor
            );
        },
        submitButtonVisible() {
            return this.diagnosisLevel === 2 || this.diagnosisLevel === 3;
        },
        issueButtonVisible() {
            return this.diagnosisLevel === 3;
        },
        auditButtonVisible() {
            return this.diagnosisLevel === 4;
        },
        finalJudgeButtonVisible() {
            return this.diagnosisLevel === 5;
        },
        finishLabel() {
            switch (this.diagnosisLevel) {
                case 3:
                    return '核发';
                case 4:
                    return '审核';
                case 5:
                    return '终审';
                default:
                    return '';
            }
        },
    },
    methods: {
        handleClick() {
            console.log('handleClick');
        },
        dictionariesRequest(dictMap) {
            // 字典数据请求
            dictMap.forEach(async (map) => {
                const res = await this.$axios({
                    method: 'GET',
                    url: '/PROXY-Remote/dicts/list',
                    params: { code: map.code, page: 0, size: 99 },
                });

                if (res && res.data.code === 200) {
                    const result = res.data;
                    result.data.forEach((t) => {
                        this[map.array].push({ id: t.id, label: t.name });
                    });
                }
            });
        },

        // 诊断 - 搜索
        diagnosisSearch() {
            if (this.searchPathologyId !== this.diagnosisPathologyId) {
                this.$emit('diagnosisSearch', this.searchPathologyId);
            }
        },
        // TODO 诊断 - 上一个
        diagnosisLast() {
            console.log('diagnosisLast');
        },
        // TODO 诊断 - 下一个
        diagnosisNext() {
            console.log('diagnosisNext');
        },
        // TODO 诊断 - 检验分析
        diagnosisCheckAnalysis() {
            console.log('diagnosisCheckAnalysis');
        },
        // TODO 加做项目
        specialExtraDialogOpen() {
            console.log('specialExtraDialogOpen');
        },
        techExtraDialogOpen() {
            console.log('techExtraDialogOpen');
        },
        // TODO 收藏 - 改变
        collectChange() {
            this.isCollected = !this.isCollected;
        },
        // TODO 报告 - 查看
        reportView() {
            console.log('reportView');
        },
        // TODO 报告 - 回收
        reportCallBack() {
            console.log('reportCallBack');
        },
        // TODO 报告 - 延期
        reportDelay() {
            console.log('reportDelay');
        },
        // 诊断 - 保存
        async diagnosisSave() {
            const detailString = JSON.stringify(this.detailForm);
            const { state } = this.$store;
            const res = await this.$axios({
                url: `/PROXY-Remote/diagnosis/${this.diagnosisId}/next-flow`,
                method: 'PUT',
                data: {
                    isTempStorage: 1,
                    doctorId: state.user.id,
                    detailString,
                },
            });

            if (res && res.data.code === 200) {
                this.$message.success('保存成功');
            } else {
                this.$message.error('保存失败');
            }
        },
        // 诊断 - 提交
        diagnosisCommit() {
            this.submitDialogOpen(this.diagnosisLevel, false);
        },
        // 诊断 - 核发
        diagnosisIssue() {
            if (this.isNeedFinalJudge) {
                this.submitDialogOpen(this.diagnosisLevel, true);
            } else {
                this.diagnosisFinishRequest();
            }
        },
        // 诊断 - 审核
        diagnosisAudit() {
            if (this.isNeedFinalJudge) {
                this.submitDialogOpen(this.diagnosisLevel, true);
            } else {
                this.diagnosisFinishRequest();
            }
        },
        // 诊断 - 终审
        diagnosisFinalJudge() {
            this.diagnosisFinishRequest();
        },
        // 诊断 - 请求结束诊断 (核发/审核/终审)
        async diagnosisFinishRequest() {
            const detailString = JSON.stringify(this.detailForm);
            const { state } = this.$store;

            await this.$axios({
                url: `/PROXY-Remote/diagnosis/${this.diagnosisId}/next-flow`,
                method: 'PUT',
                data: {
                    isTempStorage: 0,
                    doctorId: state.user.id,
                    detailString,
                    level: 6,
                },
            }).then((res) => {
                // 请求失败
                if (res.data.code !== 200) {
                    this.$message.error(`${this.finishLabel}失败`);
                    throw new Error(res.data);
                }

                // 请求成功
                this.$message.success(`${this.finishLabel}成功`);
            });
        },
        // TODO 诊断 - 讨论
        diagnosisDiscussion() {
            console.log('diagnosisDiscussion');
        },
        // TODO 诊断 - 转院外
        diagnosisSendOut() {
            console.log('diagnosisSendOut');
        },
        // TODO 诊断 - 退回
        diagnosisDrawBack() {
            console.log('diagnosisDrawBack');
        },
        // TODO 诊断 - 重新扫描
        diagnosisRescan() {
            console.log('diagnosisDrawBack');
        },
        // 检查类型 - 变更
        checkCategoryChange(val) {
            this.$confirm(
                '切换检查类型将导致填写数据丢失, 是否继续？',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(async () => {
                    this.diagnosis.checkCategory = val;
                    await this.diagnosisDialogSave();
                    await this.reportTemplateRequest();
                })
                .catch(() => {
                    this.checkCategorySelected = this.diagnosis.checkCategory;
                });
        },
        // 检查类型 - 变更后保存
        async diagnosisDialogSave() {
            const res = await this.$axios({
                // 详见 axios 请求配置项
                method: 'PUT',
                url: '/PROXY-Remote/diagnosis',
                data: {
                    id: this.diagnosisId,
                    checkCategory: this.diagnosis.checkCategory,
                },
            });

            if (res && res.data.code === 200) {
                this.$message.success('切换成功');
            }
        },
        // 依据 level 获取诊断详情
        detailGetByLevel(level) {
            return this.diagnosis.diagnosisDetailList.find(
                (t) => t.currentLevel === level
            );
        },
        // 意见 - 查看他人时，保存表单数据到缓存，加载缓存数据到表单
        opinionTabChange(activeTab, oldActiveTab) {
            const that = this;
            const opinionSave = function () {
                that.detailTemp = _.clone(that.detailForm);
            };
            const opinionLoadFromLevel = function (level) {
                const { detailJson } = that.detailGetByLevel(level);
                that.detailForm = _.clone(detailJson);
            };
            const opinionLoadFromTemp = function () {
                that.detailForm = _.clone(that.detailTemp);
            };

            const activeLevel = parseInt(activeTab, 10);
            const oldActiveLevel = parseInt(oldActiveTab, 10);

            if (oldActiveLevel === this.diagnosisLevel) {
                opinionSave();
                opinionLoadFromLevel(activeLevel);
                return;
            }
            if (activeLevel === this.diagnosisLevel) {
                opinionLoadFromTemp();
                return;
            }

            opinionLoadFromLevel(activeLevel);
        },
        // 复制上一级诊断意见
        diagnosisCopy() {
            const { detailJson } = this.detailGetByLevel(
                this.diagnosisPrevLevel
            );
            this.detailForm = _.clone(detailJson);
        },
        // 报告模板获取
        async reportTemplateRequest() {
            this.reportTemplateReady = false;
            if (!this.isAssigned) {
                return;
            }
            const res = await this.$axios({
                method: 'GET',
                url: '/PROXY-Remote/report-templates/check-category',
                params: {
                    checkCategory: this.diagnosis.checkCategory,
                },
            });

            if (res && res.data.code === 200) {
                const result = res.data.data;
                this.reportTemplateCol = _.get(result, 'settingsColNum', 12);
                this.componentList = [];
                this.detailForm = _.clone({});

                result.reportTemplateComponents.forEach((t, index) => {
                    // 忽略基本信息项
                    if (t.bigType === 'base') {
                        return;
                    }
                    // 为可输入项设置初始值
                    if (
                        t.smallType === 'input' ||
                        t.smallType === 'selection'
                    ) {
                        this.detailForm[t.i] = '';
                    }

                    const item = t;
                    item.index = index;
                    this.componentList.push(item);
                });

                const { detailJson } = this.detailGetByLevel(
                    this.diagnosisLevel
                );
                Object.keys(this.detailForm).forEach((key) => {
                    this.detailForm[key] = detailJson[key]
                        ? detailJson[key]
                        : '';
                });

                // 初始化填写表单的 setter 和 getter
                this.detailForm = _.clone(this.detailForm);
            }

            this.reportTemplateReady = true;
        },
        // 报告模板组件样式
        styleString(styleJson) {
            let style = 'width: 100%; word-break:break-all;';
            Object.keys(styleJson).forEach((key) => {
                style += `${key}:${styleJson[key]};`;
            });
            return style;
        },
        // 提交对话框 - 打开
        submitDialogOpen(level, isSubmitFinalJudge) {
            this.submitDialog.isReady = false;
            this.submitDialog.visible = true;

            if (level === 2) {
                this.submitDialog.title = '选择提交的医生';
                this.submitTable.operation[0].label = '提交';
            } else if (isSubmitFinalJudge) {
                this.submitDialog.title = '选择终审的医生';
                this.submitTable.operation[0].label = '终审';
            } else if (level === 3) {
                this.submitDialog.title = '选择提交的医生';
                this.submitTable.operation[0].label = '提交';
            }
            this.submitTableDataRequest();
        },
        // 可提交医生列表
        async submitTableDataRequest() {
            this.submitDialog.isReady = false;
            const res = await this.$axios({
                method: 'GET',
                url: `/PROXY-Remote/diagnosis/${this.diagnosisId}/next-flow-doctors`,
                // TODO 分页信息
                // params: {
                //   size: this.submitTable.pageInfo.size,
                //   page: this.submitTable.pageInfo.page - 1,
                // },
            });
            if (res && res.data.code === 200) {
                const result = res.data;
                console.log('result', result);
                // TODO 分页信息
                // this.submitTable.pageInfo = {
                //   total: result.pageInfo.total,
                //   page: result.pageInfo.page + 1,
                //   size: result.pageInfo.size,
                // };
                // 查询结果数据
                this.submitTable.data = [];
                result.data.forEach((t) => {
                    const list = t.diagnosisPermissionVoList;
                    const permission = list.find(
                        (item) => item.subgroupId === this.subgroupId
                    );
                    if (permission) {
                        this.submitTable.data.push({
                            index: this.submitTable.data.length,
                            id: t.id,
                            name: t.name,
                            medicalTitleName: t.medicalTitleName,
                            level: permission.maxLevel,
                            levelName: permission.maxLevelName,
                            phone: t.phone,
                            speciality: t.speciality,
                        });
                    }
                });
            }

            this.submitDialog.isReady = true;
        },
        submitTablePageJumpTo(val) {
            this.submitTable.pageInfo.page = val;
            this.submitTableDataRequest();
        },
        submitTableSizeChange(val) {
            this.submitTable.pageInfo.size = val;
            this.submitTableDataRequest();
        },
        submitTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        // 提交确认
        submitTableSubmitConfirm(row) {
            this.$confirm('是否提交至该医生？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    const detailString = JSON.stringify(this.detailForm);

                    const res = await this.$axios({
                        url: `/PROXY-Remote/diagnosis/${this.diagnosisId}/next-flow`,
                        method: 'PUT',
                        data: {
                            isTempStorage: 0,
                            doctorId: row.id,
                            detailString,
                            level: row.level,
                        },
                    });

                    if (res && res.data.code === 200) {
                        this.$message.success('提交成功');
                    } else {
                        this.$message.error('提交失败');
                    }
                })
                .catch(() => {
                    this.$message.info('取消操作');
                });
        },
    },
};
</script>

<style scoped>
.container-narrow {
    margin: 0 auto;

    max-width: 750px;

    height: max-content;

    background: #ffffff;

    /*padding: 20px;*/
}

.button-list-item {
    /*margin-right: 10px;*/

    /*width: 90px;*/
}

.tag-list-item {
    margin-right: 10px;
}

.quality-list-item {
    width: 100px;
}

.row-in-grid-item {
    min-height: 28px;

    display: flex;

    align-items: center;
}
</style>
